package com.glowdayz.glowmee;

import java.io.IOException;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.PorterDuff;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.ContextThemeWrapper;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.glowdayz.common.ActivityManager;
import com.glowdayz.common.CDialog;
import com.glowdayz.common.PatternChecker;
import com.glowdayz.common.XmlParser;
import com.glowdayz.model.AddItem;
import com.glowdayz.model.UserInfo;
import com.google.android.gcm.GCMRegistrar;


public class JoinFirst extends Activity implements OnClickListener, TextWatcher {
	
	private ActivityManager am = ActivityManager.getInstance();
	
	EditText nickName = null, eMail = null, password1 = null, password2 = null, recommender = null;
	ImageView okBt = null;
	String url = "", eMailInfo = "", nickNameInfo = "";
	
	String regId = "", pushUrl = "";

	@SuppressLint("NewApi")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_join_first);
		
		am.addActivity(this);
		
		ImageView backBt = (ImageView) findViewById(R.id.backBt);
		backBt.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN: {
                        ImageView view = (ImageView) v;
                        view.getDrawable().setColorFilter(0x77000000,PorterDuff.Mode.SRC_ATOP);
                        view.invalidate();
                        break;
                    }
                    case MotionEvent.ACTION_UP:
                    case MotionEvent.ACTION_CANCEL: {
                        ImageView view = (ImageView) v;
                        view.getDrawable().clearColorFilter();
                        view.invalidate();
                        break;
                    }
                }
                return false;
            }
        });
		backBt.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
				//regId = GCMRegistrar.getRegistrationId(JoinFirst.this);
				//pushUrl = getResources().getString(R.string.server_url) + "/glowmee/pushXml.do?regId=" + regId + "&msg=" + "글로우미 이벤트";
				//(new PushWorker()).execute();
			}
		});
		
		TextView textTitle = (TextView) findViewById(R.id.textTitle);
		textTitle.setText("회원가입");
		
		nickName = (EditText) findViewById(R.id.nickName);
		eMail = (EditText) findViewById(R.id.eMail);
		password1 = (EditText) findViewById(R.id.password1);
		password2 = (EditText) findViewById(R.id.password2);
		recommender = (EditText) findViewById(R.id.recommender);
		
		nickName.addTextChangedListener(this);
		eMail.addTextChangedListener(this);
		password1.addTextChangedListener(this);
		password2.addTextChangedListener(this);
		
		okBt = (ImageView) findViewById(R.id.okBt);
		okBt.setEnabled(false);
		okBt.setImageAlpha(150);
		okBt.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.okBt:
			PatternChecker checker = PatternChecker.getInstance();
			
			String nickNameValue = nickName.getText().toString().trim();
			if (nickNameValue.equals("")) {
				Toast.makeText(this, "닉네임을 입력하세요.", Toast.LENGTH_SHORT).show();
				return;
			}
			
			if (nickNameValue.length() > 6) {
				Toast.makeText(this, "닉네임은 6글자 이하로 입력해 주세요.", Toast.LENGTH_SHORT).show();
				return;
			}
			
			String eMailValue = eMail.getText().toString().trim();
			if (eMailValue.equals("")) {
				Toast.makeText(this, "이메일을 입력하세요.", Toast.LENGTH_SHORT).show();
				return;
			}
			if (!checker.isEmail(eMailValue)) {
				Toast.makeText(this, "이메일 형식으로 입력해 주세요.", Toast.LENGTH_SHORT).show();
				return;
			}
			
			String password1Value = password1.getText().toString().trim();
			String password2Value = password2.getText().toString().trim();
			
			if (password1Value.equals("") || password2Value.equals("")) {
				Toast.makeText(this, "패스워드를 입력하세요.", Toast.LENGTH_SHORT).show();
				return;
			}
			
			if (password1Value.length() > 12 || password1Value.length() < 6) {
				Toast.makeText(this, "패스워드는 6글자 이상 12자 이하로 입력해 주세요.", Toast.LENGTH_SHORT).show();
				return;
			}
			
			if (!password1Value.equals(password2Value)) {
				Toast.makeText(this, "비밀번호가 일치하지 않습니다.", Toast.LENGTH_SHORT).show();
				return;
			}
			
			String recommenderValue = recommender.getText().toString().trim();
			
			regId = GCMRegistrar.getRegistrationId(JoinFirst.this);
			
			url = getResources().getString(R.string.server_url) +  "/glowmee/addRegisterXml.do?";
			url += "nickName=" + nickNameValue + "&eMail=" + eMailValue + "&password=" + password1Value + "&regId=" + regId +
					"&recommender=" + recommenderValue;
			
			nickNameInfo = nickNameValue;
			
			(new AddWorker()).execute();
			
			break;
		}
	}
	
	public class AddWorker extends AsyncTask<Object, AddItem, Object> {
		@Override
		protected void onPreExecute() {
			CDialog.showLoading(JoinFirst.this);
		}

		@Override
		protected Object doInBackground(Object... params) {
			Object result = null;
			// XML 파서 생성
			XmlPullParser parser = XmlParser.getInstance().getParser(url);
			// 통신 실패시 예외처리
			if (parser == null) {
				this.cancel(true);
				return null;
			}
			
			try {
				String tag = null;
				int type = parser.getEventType();
				
				/** 읽은 내용을 담기 위한 변수 */
				String rt = null;
				String rtmsg = null;
				int seq = 0;
				// 파싱 처리를 위한 반복 시작
				while (type != XmlPullParser.END_DOCUMENT) {
					// 읽은 태그의 이름
					tag = parser.getName();

					// 현재 읽고 있는 태그의 종류별로 분기
					switch (type) {
					case XmlPullParser.START_TAG:
						/** 원하는 종류의 시작태그를 만났을 때, 값을 추출 */
						if (tag.equals("rt")) {
							parser.next();
							rt = parser.getText();
						} else if (tag.equals("rtmsg")) {
							parser.next();
							rtmsg = parser.getText();
						} else if (tag.equals("seq")) {
							parser.next();
							seq = Integer.parseInt(parser.getText().trim());
						} else if (tag.equals("eMail")) {
							parser.next();
							eMailInfo = parser.getText();
						}
						
						break;

					case XmlPullParser.END_TAG:
						
						if (tag.equals("JSPglowmee")) {
							AddItem item = new AddItem(rt, rtmsg, seq);
							publishProgress(item);
						}
						break;
					}

					// 다음 태그로 이동하고, 상태값을 변경
					type = parser.next();
				}

			} catch (XmlPullParserException e) {
				System.out.println("파서 생성 실패 >> " + e.toString());
			} catch (IOException e) {
				System.out.println("파서 읽기 실패 >> " + e.toString());
			}
			
			return result;
		}

		@Override
		protected void onProgressUpdate(AddItem... param) {
			
			if (param[0].getRt().equals("SUCCESS")) {
				UserInfo.getInstance().setUSER_ID(param[0].getSeq());
				UserInfo.getInstance().setUSER_EMAIL(eMailInfo);
				UserInfo.getInstance().setUSER_NICKNAME(nickNameInfo);
				
				Intent intent = new Intent(JoinFirst.this, JoinSecond.class);
				intent.putExtra("PARAM_idx", param[0].getSeq());
				intent.putExtra("PARAM_nickName", nickName.getText().toString().trim());
				startActivity(intent);
			} else {
				AlertDialog.Builder alert = new AlertDialog.Builder(new ContextThemeWrapper(JoinFirst.this, android.R.style.Theme_Holo_Light_Dialog));
				alert.setTitle("가입실패");
				alert.setMessage(param[0].getRtmsg());
				alert.setCancelable(false);
				alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
					}
				});
				alert.create();
				alert.show();
			}
			
		}

		@Override
		protected void onPostExecute(Object param) {
			CDialog.hideLoading();
		}

		@Override
		protected void onCancelled() {
			CDialog.hideLoading();
			AlertDialog.Builder alert = new AlertDialog.Builder(new ContextThemeWrapper(JoinFirst.this, android.R.style.Theme_Holo_Light_Dialog));
			alert.setMessage("일시적인 통신에러입니다.");
			alert.setCancelable(false);
			alert.setPositiveButton("다시 시도", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					(new AddWorker()).execute();
				}
			});
			alert.setNegativeButton("뒤로 가기", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					finish();
				}
			});
			alert.create();
			alert.show();
		}
	}

	@Override
	public void afterTextChanged(Editable arg0) {
		
	}

	@Override
	public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
			int arg3) {
		
	}

	@SuppressLint("NewApi")
	@Override
	public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
		if (!nickName.getText().toString().equals("") && !eMail.getText().toString().equals("") && 
				!password1.getText().toString().equals("") && !password2.getText().toString().equals("")) {
			okBt.setImageAlpha(255);
			okBt.setEnabled(true);
			okBt.setOnTouchListener(new OnTouchListener() {
	            @Override
	            public boolean onTouch(View v, MotionEvent event) {
	                switch (event.getAction()) {
	                    case MotionEvent.ACTION_DOWN: {
	                        ImageView view = (ImageView) v;
	                        view.getDrawable().setColorFilter(0x77000000,PorterDuff.Mode.SRC_ATOP);
	                        view.invalidate();
	                        break;
	                    }
	                    case MotionEvent.ACTION_UP:
	                    case MotionEvent.ACTION_CANCEL: {
	                        ImageView view = (ImageView) v;
	                        view.getDrawable().clearColorFilter();
	                        view.invalidate();
	                        break;
	                    }
	                }
	                return false;
	            }
	        });
		} else {
			okBt.setImageAlpha(150);
			okBt.setEnabled(false);
		}
	}
	
	public class PushWorker extends AsyncTask<Object, AddItem, Object> {
		@Override
		protected void onPreExecute() {
			CDialog.showLoading(JoinFirst.this);
		}

		@Override
		protected Object doInBackground(Object... params) {
			Object result = null;
			
			// XML 파서 생성
			XmlPullParser parser = XmlParser.getInstance().getParser(pushUrl);
			// 통신 실패시 예외처리
			if (parser == null) {
				this.cancel(true);
				return null;
			}
			
			try {
				String tag = null;
				int type = parser.getEventType();

				/** 읽은 내용을 담기 위한 변수 */
				String rt = null;
				String rtmsg = null;
				int seq = 0;
				// 파싱 처리를 위한 반복 시작
				while (type != XmlPullParser.END_DOCUMENT) {
					// 읽은 태그의 이름
					tag = parser.getName();

					// 현재 읽고 있는 태그의 종류별로 분기
					switch (type) {
					case XmlPullParser.START_TAG:
						/** 원하는 종류의 시작태그를 만났을 때, 값을 추출 */
						if (tag.equals("rt")) {
							parser.next();
							rt = parser.getText();
						} else if (tag.equals("rtmsg")) {
							parser.next();
							rtmsg = parser.getText();
						} else if (tag.equals("seq")) {
							parser.next();
							seq = Integer.parseInt(parser.getText().trim());
						}
						
						break;

					case XmlPullParser.END_TAG:
						
						if (tag.equals("JSPglowmee")) {
							AddItem item = new AddItem(rt, rtmsg, seq);
							publishProgress(item);
						}
						break;
					}

					// 다음 태그로 이동하고, 상태값을 변경
					type = parser.next();
				}

			} catch (XmlPullParserException e) {
				System.out.println("파서 생성 실패 >> " + e.toString());
			} catch (IOException e) {
				System.out.println("파서 읽기 실패 >> " + e.toString());
			}
			
			return result;
		}

		@Override
		protected void onProgressUpdate(AddItem... param) {
			
			if (param[0].getRt().equals("SUCCESS")) {
				AlertDialog.Builder alert = new AlertDialog.Builder(new ContextThemeWrapper(JoinFirst.this, android.R.style.Theme_Holo_Light_Dialog));
				alert.setTitle("푸쉬 성공");
				alert.setMessage(param[0].getRtmsg());
				alert.setCancelable(false);
				alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
					}
				});
				alert.create();
				alert.show();
			} else {
				AlertDialog.Builder alert = new AlertDialog.Builder(new ContextThemeWrapper(JoinFirst.this, android.R.style.Theme_Holo_Light_Dialog));
				alert.setTitle("푸쉬 실패");
				alert.setMessage(param[0].getRtmsg());
				alert.setCancelable(false);
				alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
					}
				});
				alert.create();
				alert.show();
			}
			
		}

		@Override
		protected void onPostExecute(Object param) {
			CDialog.hideLoading();
		}
		
		@Override
		protected void onCancelled() {
			CDialog.hideLoading();
			AlertDialog.Builder alert = new AlertDialog.Builder(new ContextThemeWrapper(JoinFirst.this, android.R.style.Theme_Holo_Light_Dialog));
			alert.setMessage("일시적인 통신에러입니다.");
			alert.setCancelable(false);
			alert.setPositiveButton("다시 시도", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					(new PushWorker()).execute();
				}
			});
			alert.setNegativeButton("뒤로 가기", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					finish();
				}
			});
			alert.create();
			alert.show();
		}
	}
	
    @Override
	protected void onDestroy() {
		super.onDestroy();
		am.removeActivity(this);
	}

}
